import config from './config'
import axios from "axios";
import router from "@/router";
import { ElMessage } from 'element-plus';

const baseUrl = config.baseUrl

const func = {
    uploadUrl: function(api=undefined) {
        api = api || '/ajax/upload'
        let user = func.getUser();
        let access_token = user.access_token || ''
        return `${baseUrl}${api}?access_token=${access_token}`
    },
    request: function (url_path, params) {
        let user =  func.getUser();
        return axios.post(`${baseUrl}${url_path}`, params, {
            headers: {
                "Authorization": 'Bearer ' + (user.access_token || ''),
                "Content-Type": 'application/x-www-form-urlencoded',
            },
        }).then(res => {
            if (res.data.code !== 1) {
                ElMessage({
                    message: res.data.msg,
                    type: 'error'
                });
            }
            if (res.data.code === 301) {
                router.push({path:'/login'});
            }
            return res.data
        });
    },
    getConfig: function (name) {
        return config[name] || ''
    },
    dateFormat(time, format) {
        if (!time) {
            return ''
        }
        if (!format) {
            format='Y-m-d H:i:s'
        }
        var date = new Date(parseInt(time) * 1000)
        var Y = date.getFullYear()
        var m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
        var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var i = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return format.replace('Y', Y).replace('m', m).replace('d', d).replace('H', H).replace('i', i).replace('s', s)
    },
    setUser: (user)=>{
        localStorage.setItem('admin', JSON.stringify(user));
    },
    getUser: ()=>{
        return JSON.parse(localStorage.getItem('admin')) || {}
    },
    delUser: ()=>{
        localStorage.removeItem('admin');
    },
}

export default func